<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Index_Index extends Controller_Index_Base
{
    public function action_index()
    {  
        $company = ORM::factory('company')->get_current();
        if ($company) {
            Request::current()->redirect('http://'.$company->domain.'.'.Model_Main::get_base_domain().'/dashboard');   
        }
      
        if (HTTP_Request::POST == $this->request->method()) {            
            $email    = $this->request->post('email');
                  
            try {                
                $user  = ORM::factory('user')->add_user_for_ref_system($email);                                
                $_POST = array();
                 
                Request::current()->redirect('/success?code='.$user->ref_code); 
            } catch (Exception $e) {
                $message = 'Форма заполнена с ошибками!';
                if (strstr($e->getMessage(), 'Duplicate entry') !== false) {
                    $message = 'Данный e-mail или домен уже зарегистрированы';
                }
            }
        }
               
        $content = new View('index/index/index_tpl');      
        $this->print_template('Help Desk система для поддержки клиентов TeamDesk.ru | Бесплатный Helpdesk / Хелпдеск / Тикет система', $content); 
    }
    
    public function action_register()
    {
        if (isset($_GET['check_email'])) {
            $email  = $_GET['email'];
            
            if (Model_User::check_email($email)) {
                echo 'true';
                die();    
            }  
            echo 'false';
            die();
        }
        
        if (isset($_GET['check_domain'])) {
            $domain  = $_GET['domain'];
            
            if (Model_Company::check_domain($domain)) {
                echo 'true';
                die();    
            }  
            echo 'false';
            die();            
        }
        
        if (HTTP_Request::POST == $this->request->method()) {            
            $email    = $this->request->post('email');
            //$password = $this->request->post('password');
            $url      = $this->request->post('url');
            
            $firstname  = $this->request->post('firstname'); 
            $phone      = $this->request->post('phone');
            $email      = $this->request->post('email');
            $password   = $this->request->post('password');
            $domain     = $this->request->post('domain');
                  
            try {
                           
                $company = ORM::factory('company')->add_company($domain, $phone);
                $user    = ORM::factory('user')->add_user($company, $email, $firstname, $password);                                
                $_POST = array();
                
                Model_Mailer::register_company($company, $user);
                 
                Model_Auth::instance()->login($email, $password, true);
                
                //Request::current()->redirect('http://'.$company->domain.'.'.Model_Main::get_base_domain().'/mailbox/add');
                Request::current()->redirect('/success?domain='.$company->domain);                     
            } catch (Model_Exception $e) {
                
            }
        }
        
        $content = new View('index/index/register_tpl');      
        $this->response->body($content);
    }
    
    public function action_login()
    {    
        $errors = array();       
        if (HTTP_Request::POST == $this->request->method()) {
            $email    = $this->request->post('email');
            $password = $this->request->post('password');
            //$redirect_url = $this->request->post('redirect_url');
                  
            try {
                Model_Auth::instance()->logout();
                Model_Auth::instance()->login($email, $password, true);                
                $_POST = array(); 
                
                if (Model_Auth::instance()->logged_in()) {
                    $user = Model_Auth::instance()->get_user();
                    $company = ORM::factory('company', $user->company_id); 
                    
                    Request::current()->redirect('http://'.$company->domain.'.'.Model_Main::get_base_domain().'/dashboard');     
                } else {
                    if (Model_User::check_email($email)) {
                        $errors['email'] = 'Нет такого Email';    
                    }
                    $errors['password'] = 'Неправильный пароль';         
                }                       
            } catch (Model_Exception $e) {
                //$this->add_message($e->getMessage());
            }
        }
        $content = new View('index/index/login_tpl');
        $content->errors = $errors;
        $this->response->body($content);        
    }
    
    public function action_logout()
    {
        Model_Auth::instance()->logout(); 
        Request::current()->redirect('/login');  
    }
    
    public function action_terms()
    {               
        $content = new View('index/index/terms_tpl');      
        $this->print_template('Пользовательское соглашение - Help Desk система для поддержки клиентов TeamDesk.ru', $content); 
    }
    
    public function action_success()
    {               
        $content = new View('index/index/success_tpl');
        if (isset($_GET['domain'])) {
            $content = new View('index/index/success2_tpl');   
        }      
        $this->response->body($content);
    }
    
    public function action_blogsubscribe()
    {   
        if (HTTP_Request::POST == $this->request->method()) {
            $email    = $this->request->post('email');
                  
            try {
                file_put_contents(APPPATH.'../data/blogsubscribe.txt', trim($email)."\r\n", FILE_APPEND);
            
                $content = new View('index/index/blogsubscribe_tpl');      
                $this->response->body($content);                            
            } catch (Model_Exception $e) {
                //$this->add_message($e->getMessage());
            }
        }
    }
    
    /*public function action_search()
    {
        $query = strip_tags($this->request->param('query'));       
        $models = ORM::factory('model')->search($query);
        $content = new View('index/index/search_tpl'); 
        $content->models = $models;       
        $this->print_template('Поиск - '.$query, $content);
    }   */
} 
